package cn.com.connext.scrm.web.rest;

import cn.com.connext.scrm.domain.master.MdmHelpMsg;
import cn.com.connext.scrm.domain.master.MsgTemplateInfo;
import cn.com.connext.scrm.service.MdmHelpMsgService;
import cn.com.connext.scrm.service.dto.JsonResult;
import cn.com.connext.scrm.utils.RedisUtils;
import cn.com.connext.scrm.web.rest.vm.MdmHelpMsgVM;
import cn.com.connext.scrm.web.rest.vm.MemberVM;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.connext.common.web.rest.BaseResource;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.*;
import java.util.List;
import java.util.concurrent.TimeoutException;

/**助力信息
 * Created by WangZhan on 2019/01/24.
 */
@RestController
@RequestMapping("/api/mdmhelpmsg")
public class MdmHelpMsgResource extends BaseResource {
    private final Logger log = LoggerFactory.getLogger(MdmHelpMsgResource.class);

    @Autowired
    private MdmHelpMsgService mdmHelpMsgService;
    public MdmHelpMsgResource() throws TimeoutException {
        super("MdmHelpMsg");
    }

    /**
     * 帮助助力接口
     */
    @PostMapping("/add")
    @ApiOperation(value = "帮助助力", notes = "帮助助力活动")
    public JsonResult create(@RequestBody MdmHelpMsgVM req) {
        log.info("帮助助力，入参req : {}", JSON.toJSONString(req));
        return mdmHelpMsgService.save(req);
    }
    /**
     *检查该用户是否可以助力
     */
    @PostMapping("/checkUserIsExist")
    @ApiOperation(value = "检查该用户是否可以助力", notes = "检查该用户是否可以助力")
    public JsonResult checkUserIsExist(@RequestBody MdmHelpMsgVM req) {
        log.info("检查该用户是否可以助力，入参req : {}", JSON.toJSONString(req));
        return mdmHelpMsgService.checkUserIsExist(req);
    }




    /**
     * 查看助力用户信息
     */
    @PostMapping("/findByActivityIdAndCreateUserId")
    @ApiOperation(value = "查看助力用户信息", notes = "查看助力用户信息")
    public JsonResult findByActivityIdAndCreateUserId(@RequestBody MdmHelpMsg req) {
        log.info("查看助力用户信息，入参req : {}", JSON.toJSONString(req));
        return mdmHelpMsgService.findByActivityIdAndCreateUserId(req);
    }


    /**
     * 检查是否需要提示助力已满
     */
    @PostMapping("/findIsNeedPrompt")
    @ApiOperation(value = "检查是否需要提示助力已满", notes = "检查是否需要提示助力已满")
    public JsonResult findIsNeedPrompt(@RequestBody MdmHelpMsg req) {
        log.info("检查是否需要提示助力已满，入参req : {}", JSON.toJSONString(req));
        return mdmHelpMsgService.findIsNeedPrompt(req);
    }

    /**
     * 查询助力活动奖品发放情况
     */
    @PostMapping("/findMdmHelpActivityPrize")
    @ApiOperation(value = "查询助力活动奖品发放情况", notes = "查询助力活动奖品发放情况")
    public JsonResult findMdmHelpActivityPrize(@RequestBody MdmHelpMsgVM vm) {
        log.info("查询助力活动奖品发放情况，入参req : {}", JSON.toJSONString(vm));
        return mdmHelpMsgService.findMdmHelpActivityPrize(vm);
    }

    @Autowired
    private RedisUtils redisUtils;
    /**
     * 查询会员是否已注册
     */
    @PostMapping("/getMemberIsRegister")
    @ApiOperation(value = "查询会员是否已注册", notes = "查询会员是否已注册")
    public JsonResult getMemberIsRegister(@RequestBody MemberVM vm) {
        String sessionId =vm.getSessionId();
        String encryptedData =vm.getEncryptedData();
        String iv =vm.getIv();
        //从缓存中获取session_key
        log.info("sessionId:{},data:{},iv:{}", sessionId, encryptedData, iv);
        Object wxSessionObj = redisUtils.get(sessionId);
        if (null == wxSessionObj) {
            return null;
        }
        log.info("wxSessionObj:{},data:{},iv:{}", wxSessionObj, encryptedData, iv);
        String wxSessionStr = (String) wxSessionObj;
        String sessionKey = wxSessionStr;

        try {
            byte[] resultByte = decrypt(org.apache.commons.codec.binary.Base64.decodeBase64(encryptedData),
                org.apache.commons.codec.binary.Base64.decodeBase64(sessionKey),
                org.apache.commons.codec.binary.Base64.decodeBase64(iv));
            if (null != resultByte && resultByte.length > 0) {
                String oldUserInfo = new String(resultByte, "UTF-8");
                log.error("oldUserInfo:" + oldUserInfo);
                JSONObject jsonObject = JSONObject.parseObject(oldUserInfo);
                if (StringUtils.isNotEmpty(jsonObject.getString("purePhoneNumber"))) {
                    //绑定手机号
                    String mobile = jsonObject.getString("purePhoneNumber");
                    //设置手机号
                    vm.setMobile(mobile);
                }
            }
        } catch (InvalidAlgorithmParameterException | UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        log.info("查询会员是否已注册，入参req : {}", JSON.toJSONString(vm));
        return mdmHelpMsgService.getMember(vm.getUnionId(),vm.getMobile());
    }

    @PostMapping("/getHelpMessageList")
    @ApiOperation(value = "获取消息通知列表", tags = {"详细通知"}, notes = "列表")
    public JsonResult getHelpMessage() {
        JsonResult jsonResult = new JsonResult();
        List<MsgTemplateInfo> list = mdmHelpMsgService.getHelpMessage();
        jsonResult.setData(list);
        return jsonResult;
    }


    private byte[] decrypt(byte[] content, byte[] keyByte, byte[] ivByte) throws InvalidAlgorithmParameterException {
        //initialize();
        try {
            /**
             * 这个地方调用BouncyCastleProvider
             *让java支持PKCS7Padding
             */
            Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
            SecretKeySpec sKeySpec = new SecretKeySpec(keyByte, "AES");
            AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
            parameters.init(new IvParameterSpec(ivByte));
            cipher.init(Cipher.DECRYPT_MODE, sKeySpec, parameters);// 初始化
            byte[] result = cipher.doFinal(content);

            return result;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
}
